package br.com.fatecjp.pooai.gerenciador.taxi.mobile.ui;

import jade.core.MicroRuntime;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;

import br.com.fatecjp.pooai.gerenciador.taxi.mobile.client.AgenteCliente;

public class NameInputDialog extends Form implements CommandListener {

	private TextField nameTextField;
	private TextField xOrigemTextField;
	private TextField yOrigemTextField;
	private TextField xDestinoTextField;
	private TextField yDestinoTextField;

	private StringItem msgStatus;

	private Command comandoOk;
	private Command comandoCancelar;

	public NameInputDialog() {
		super("Gerenciador de Táxi");
		this.inicializar();
	}

	private void inicializar() {
		this.inicializarComponentes();
		this.inicializarComandos();
	}

	private void inicializarComponentes() {
		this.nameTextField = new TextField("Nome: ", null, 32, TextField.ANY);
		this.append(this.nameTextField);
		this.xOrigemTextField = new TextField("X da origem: ", null, 2,
				TextField.NUMERIC);
		this.append(this.xOrigemTextField);
		this.yOrigemTextField = new TextField("Y da origem: ", null, 2,
				TextField.NUMERIC);
		this.append(this.yOrigemTextField);
		this.xDestinoTextField = new TextField("X do destino: ", null, 2,
				TextField.NUMERIC);
		this.append(this.xDestinoTextField);
		this.yDestinoTextField = new TextField("Y do destino: ", null, 2,
				TextField.NUMERIC);
		this.append(this.yDestinoTextField);
		this.msgStatus = new StringItem(null, null);
		this.append(this.msgStatus);
	}

	private void inicializarComandos() {

		this.comandoOk = new Command("Ok", Command.OK, 1);
		this.comandoCancelar = new Command("Cancelar", Command.CANCEL, 1);

		this.addCommand(this.comandoOk);
		this.addCommand(this.comandoCancelar);

		this.setCommandListener(this);

	}

	public void commandAction(Command c, Displayable d) {

		if (c == this.comandoOk) {

			String nome = this.nameTextField.getString();
			String[] args = new String[4];
			args[0] = this.xOrigemTextField.getString();
			args[1] = this.yOrigemTextField.getString();
			args[2] = this.xDestinoTextField.getString();
			args[3] = this.yDestinoTextField.getString();
			try {
				MicroRuntime.startAgent(nome, AgenteCliente.class.getName(),
						args);
				this.msgStatus.setText("Taxi solicitado com sucesso.");
			} catch (Exception e) {
				this.msgStatus.setText("O nome informado já está em uso.");
			}

		} else if (c == this.comandoCancelar) {
			MicroRuntime.stopJADE();
		}

	}

}
